package cn.itsource.org.service.impl;

import cn.itsource.basic.base.service.impl.BaseServiceImpl;
import cn.itsource.org.domain.Department;
import cn.itsource.org.mapper.DepartmentMapper;
import cn.itsource.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;


    //自己单独业务
    @Override
    @Transactional
    public void add(Department department) {
        departmentMapper.insert(department);
        this.update(department);
    }

    @Override
    @Transactional
    public void update(Department department) {
        if(department.getParent() == null){
            department.setDirPath("/"+department.getId());
        }else{
            Department dadDepartment = departmentMapper.loadById(department.getParent().getId());
            department.setDirPath(dadDepartment.getDirPath()+"/"+department.getId());
        }
        departmentMapper.update(department);
    }


    @Override
    public List<Department> queryTree() {
        //查询出所有数据
        List<Department> allDepts = departmentMapper.loadAll();

        // 把所有的数据转换成Map结构--后面查找自己的上级使用
        HashMap<Long, Department> deptMap = new HashMap<>();
        for(Department dept : allDepts){
            deptMap.put(dept.getId(), dept);
        }
        //准备要返回的无限极树，把顶级部门全放到fistDepts集合中
        List<Department> firstDepts = new ArrayList<>();

        for (Department dept : allDepts) {
            //1.从所有数据中找出第一层级 firstDept   我们需要返回的数据
            if(dept.getParent_id() == null || dept.getParent_id().intValue() == 0 ){
                firstDepts.add(dept);//最顶层的数据
            }else{
                //这里拿到的是有爹的部门
                Department dadDepartment = deptMap.get(dept.getParent_id());
                //判断爹时候存在
                if(dadDepartment != null){
                    //如果存在，把自己装到爹的children里
                    dadDepartment.getChildren().add(dept);
                }

            }
        }
        return firstDepts;
    }
}
